﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace Services
{
    public class LinqExpressHelper
    {
        #region 注释例子
         
        ///// <summary>
        ///// 根据单据号获取数据
        ///// </summary>
        ///// <typeparam name="T"></typeparam>
        ///// <param name="Code">单据号</param>
        ///// <returns>Instance.MaterialService.GetEntityList<T>(i=>i.Code == Code);</returns>
        //public List<T> GetByCode<T>(string Code) where T : class
        //{
        //    var param = Expression.Parameter(typeof(T), "i");
        //    var body = Expression.Equal(Expression.Property(param, "Code"), Expression.Constant(Code));
        //    var expression = Expression.Lambda<Func<T, bool>>(body, param);
        //    //return Instance.MaterialService.GetEntityList<T>(expression);
        //}

        #endregion

        /// <summary>
        /// 根据属性查询   c=>c.propertyName == propertyValue
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="propertyName"></param>
        /// <param name="propertyValue"></param>
        /// <returns></returns>
        public static Expression<Func<T, bool>> GetLinqLambda<T>(string propertyName, string propertyValue) where T : class
        {
            ParameterExpression paraExp = Expression.Parameter(typeof(T), "c");
            ConstantExpression leftExp = Expression.Constant(propertyValue, typeof(string));
            Expression rightExp = Expression.Property(paraExp, propertyName);
            BinaryExpression binaryExp = Expression.Equal(rightExp, leftExp);//二元表达式 (c=>c.propertyName == propertyValue)
            Expression<Func<T, bool>> queryLambda = Expression.Lambda<Func<T, bool>>(binaryExp, new ParameterExpression[] { paraExp });
            return queryLambda;
        }


        //public static Expression<Func<T, bool>> GetLinqLambda<T, S>(string propertyName, S KeyId)
        //    where T : class
        //{
        //    ParameterExpression paraExp = Expression.Parameter(typeof(T), "c");
        //    ConstantExpression leftExp = Expression.Constant(KeyId, typeof(S));
        //    Expression rightExp = Expression.Property(paraExp, propertyName);
        //    BinaryExpression binaryExp = Expression.Equal(rightExp, leftExp);
        //    Expression<Func<T, bool>> queryLambda = Expression.Lambda<Func<T, bool>>(binaryExp, new ParameterExpression[] { paraExp });
        //    return queryLambda;
        //}
        //public static Expression<Func<T, S>> GetLinqLambda<T, S>(string propertyName)
        //    where T : class
        //{
        //    ParameterExpression paraExp = Expression.Parameter(typeof(T), "c");
        //    Expression rightExp = Expression.Property(paraExp, propertyName);
        //    return Expression.Lambda<Func<T, S>>(rightExp, paraExp);
        //}

    }
}
